//
//  XiuGaiBeiZhuViewController.m
//  DPGJ
//
//  Created by ZhuoLaiQiang@Gmail.com on 11-11-24.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "XiuGaiBeiZhuViewController.h"
#import "CONSTS.h"
#import "URLFactory.h"
#import "MyOrderOrderDtailViewController.h"

@interface CustonScrollView : UIScrollView

@end

@implementation CustonScrollView

//重载这个函数主要是为了收起键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

    NSArray *subViewArray = self.subviews;
    
    for (UIView *view in subViewArray)
    {
        if ([view isKindOfClass: [UITextView class]])
        {
            [((UITextView *)view) resignFirstResponder];
        }
    }
}

@end



@interface XiuGaiBeiZhuViewController() 

- (void)sendBeiZhu;
- (void)sendBeiZhuIsEnd:(TaoBaoServer *)sendBeiZhuTaoBaoServer_;
- (void)xiuGaiBeiZhu;

@end


@implementation XiuGaiBeiZhuViewController

@synthesize tid                                     =                               _tid;
@synthesize sendBeiZhuTaoBaoServer                  =                               _sendBeiZhuTaoBaoServer;
@synthesize oldBeiZhu                               =                               _oldBeiZhu;
@synthesize showBeiObject                           =                               _showBeiObject;


- (void)dealloc
{
    LF_RELEASE_SAFELY(_tid);
    LF_RELEASE_SAFELY(_sendBeiZhuTaoBaoServer);
    LF_RELEASE_SAFELY(_oldBeiZhu);
    LF_RELEASE_SAFELY(_showBeiObject);
    
    [_beiZhuTextView release];
    [super dealloc];
}

- (id)initWithTid:(NSString *)tid_ oldBeiZhu:(NSString *)oldBeiZhu_
{
    self = [super init];
    if (self) 
    {
        self.tid = tid_;
        self.oldBeiZhu = oldBeiZhu_;
    }
    return self;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"备忘";
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle: @"发送" 
                                                                               style: UIBarButtonItemStylePlain 
                                                                              target: self 
                                                                              action: @selector(sendBeiZhu)] autorelease];
    self.view.backgroundColor = [UIColor scrollViewTexturedBackgroundColor];
    
    self.navigationController.navigationBar.backgroundColor = [UIColor scrollViewTexturedBackgroundColor];
    
    _flag = 0;  //缺省的小红旗----->灰色
    
    _scrollView = (CustonScrollView *)[self.view viewWithTag: 101];
    _scrollView.contentSize = CGSizeMake(320, 416);
    
	//textView.font = textFie1.font;
	_beiZhuTextView.text = @"";
	_beiZhuTextView.returnKeyType = UIReturnKeyDone;
	_beiZhuTextView.tag = 500;
	//textView.keyboardType = UIReturnKeyDone;	// use the default type input method (entire keyboard)
	_beiZhuTextView.scrollEnabled = YES;
	_beiZhuTextView.layer.cornerRadius = 6;
	_beiZhuTextView.layer.masksToBounds = YES;
	_beiZhuTextView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    _beiZhuTextView.delegate = self;
    
    if (![_oldBeiZhu isEqualToString: MAI_JIA_MEI_YOU_TIAN_XIE_BEI_ZHU])
    {
        _beiZhuTextView.text = _oldBeiZhu; 
    }
}

- (void)viewWillAppear:(BOOL)animated 
{
	[super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)viewWillDisappear:(BOOL)animated 
{
    [super viewWillDisappear: animated];
    
    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
}

- (void)viewDidDisappear:(BOOL)animated 
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
}

- (void)keyboardWillShow:(NSNotification *)aNotification 
{
	CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval animationDuration =
	[[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect frame = _scrollView.frame;
    frame.size.height -= keyboardRect.size.height;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    _scrollView.frame = frame;
    [UIView commitAnimations];
}

- (void)keyboardWillHide: (NSNotification *)aNotification
{
    // the keyboard is hiding reset the table's height
	CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval animationDuration =
	[[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect frame = _scrollView.frame;
    frame.size.height += keyboardRect.size.height;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    _scrollView.frame = frame;
    [UIView commitAnimations];
}


- (void)viewDidUnload
{
    [_beiZhuTextView release];
    _beiZhuTextView = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}



#pragma mark - 自定义函数
- (void)sendBeiZhu
{
    /*
     tid	Number	必须	123		 交易编号
     memo	String	可选	交易备忘		 交易备忘。最大长度: 1000个字节
     flag	Number	可选	1		 交易备忘旗帜，可选值为：0(灰色), 1(红色), 2(黄色), 3(绿色), 4(蓝色), 5(粉红色)，默认值为0
     reset	Boolean	可选	true	false	 是否对memo的值置空 若为true，则不管传入的memo字段的值是否为空，都将会对已有的memo值清空，慎用； 若用false，则会根据memo是否为空来修改memo的值：若memo为空则忽略对已有memo字段的修改，若memo非空，则使用新传入的memo覆盖已有的memo的值
     */

     ITTDINFO(@"%@", _tid);
    NSString *tempMemo = [_beiZhuTextView text];
     tempMemo = [tempMemo stringByReplacingOccurrencesOfString: @" " withString: @""];
    if (!tempMemo || [tempMemo isEqualToString: @""]) 
    {
        showAlert(ALERT_TITLE, @"请填写备忘");
        
        return;
    }
    
    [_beiZhuTextView resignFirstResponder];
    
    NSString *memo = _beiZhuTextView.text;
    NSString *flag = [NSString stringWithFormat: @"%d", _flag];
    ITTDINFO(@"%@", flag);
    NSString *reset = @"false";
    NSString *api_get_taobao_trade_memo_update_str = [URLFactory get_taobao_trade_memo_updateWithTid: _tid 
                                                                                                memo: memo 
                                                                                                flag: flag 
                                                                                               reset: reset];
    
    ITTDINFO(@"%@", api_get_taobao_trade_memo_update_str);
    
    self.sendBeiZhuTaoBaoServer = [[[TaoBaoServer alloc] initWithUrl: api_get_taobao_trade_memo_update_str 
                                                               object: self 
                                                   requestIsEndSelect: @selector(sendBeiZhuIsEnd:) 
                                                  requestIsFailSelect: nil
                                                         showWaitView: YES  
                                                            urlEncode: NO] autorelease];
    
    [self.sendBeiZhuTaoBaoServer startAsynchronousRequest];
    
}

- (IBAction)flagButtonIsPressed:(UIButton *)sender 
{
    sender.selected = !(sender.selected);
    UIButton *button = (UIButton *)[self.view viewWithTag: 200 + _flag];
    button.selected = NO;
    
    if (sender.selected)
    {
        _flag = sender.tag - 200;
    }else
    {
    _flag = 0;
    }
    
    ITTDINFO(@"_flag = %d", _flag);
}

- (void)sendBeiZhuIsEnd:(TaoBaoServer *)sendBeiZhuTaoBaoServer_
{
    BOOL successSign = verifyServerRetunSuccess(sendBeiZhuTaoBaoServer_.dic);
    
    if (successSign)
    {
        showAlert(ALERT_TITLE,  @"备忘成功");
        [self xiuGaiBeiZhu];
    }else
    {
        showAlert(ALERT_TITLE,  @"备忘失败");
    }
}

//修改上级页面显示“备忘”的地方
- (void)xiuGaiBeiZhu
{
    if (_showBeiObject)
    {
        if ([_showBeiObject isKindOfClass: [MyOrderOrderDtailViewController class]]) 
        {
            MyOrderOrderDtailViewController *myOrderOrderDtailViewController = (MyOrderOrderDtailViewController *)_showBeiObject;
            [myOrderOrderDtailViewController xiuGaiBeiZhu: _beiZhuTextView.text];
        }
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [_beiZhuTextView resignFirstResponder];
}

@end
